package com.wz.project.system.dayReport.controller;

import com.wz.common.utils.StringUtils;
import com.wz.common.utils.poi.ExcelUtil;
import com.wz.common.utils.security.ShiroUtils;
import com.wz.framework.aspectj.lang.annotation.Log;
import com.wz.framework.aspectj.lang.enums.BusinessType;
import com.wz.framework.web.controller.BaseController;
import com.wz.framework.web.domain.AjaxResult;
import com.wz.framework.web.page.TableDataInfo;
import com.wz.project.system.dayReport.entity.DayReport;
import com.wz.project.system.dayReport.repository.DayReportDao;
import com.wz.project.system.dayReport.service.DayReportService;
import com.wz.project.system.employee.domain.Employee;
import com.wz.project.system.employee.service.EmployeeService;
import com.wz.project.system.user.domain.User;
import com.wz.project.system.user.domain.UserRole;
import com.wz.project.system.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/system/report")
public class DayReportController extends BaseController {

    String prefix = "system/report";

    @Autowired
    private DayReportService day_reportService;
    @Autowired
    private IUserService userService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private  DayReportDao dayReportDao;

    @PostMapping("/list")
    @ResponseBody
    public Object findAll(DayReport dayReport,Integer pageNum,Integer pageSize) {
        User user = userService.selectUserByLoginName(ShiroUtils.getLoginName());
        UserRole role = userService.selectUserRoleByUserId(user.getUserId()).get(0);
        if (ShiroUtils.getLoginName().equals("admin") || role.getRoleId() == 3) {
            //超级管理员、普通管理员
            startPage();
            Page<DayReport> all = day_reportService.findAllByParam(dayReport, pageNum, pageSize);
            System.out.println("all.size="+all.toList().size());
            TableDataInfo dataTable = getDataTable(all.toList());
            dataTable.setTotal(all.getTotalElements());
            return dataTable;
        } else {
            //普通员工
            String staffName = getEmployee().getName();
            dayReport.setStaffName(staffName);
            startPage();
            Page<DayReport> all = day_reportService.findAllByParam(dayReport,pageNum,pageSize);
            TableDataInfo dataTable = getDataTable((all).toList());
            dataTable.setTotal(all.getTotalElements());
            return dataTable;
        }
    }


    @GetMapping("/add")
    public String add(ModelMap map) {
        DayReport dayReport = new DayReport();
        if (!ShiroUtils.getLoginName().equals("admin")) {
            dayReport.setStaffStation(employeeService.selectPostByEmployee(getEmployee().getEmployeeId()).get(0).getPostName());
            dayReport.setStaffName(getEmployee().getName());
            dayReport.setFlag("0");//默认未更新
            map.put("addReport", dayReport);
            return prefix + "/add";
        } else {
            dayReport.setStaffName(null);
            map.put("addReport", dayReport);
            return prefix + "/add";
        }
    }

    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(DayReport dayReport) throws Exception {
        dayReport.setStartTime(new Date());
        dayReport.setFlag("0");//默认未更新
        day_reportService.save(dayReport);
        return AjaxResult.success();
    }

    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult update(DayReport day_report) {
        try {
            DayReport oldReport = day_reportService.findById(day_report.getReportId());
            if (StringUtils.isEmpty(day_report.getFinishWork()) || day_report.getFinishWork().equals(oldReport.getFinishWork())){
                day_report.setFlag("0");
            }else {
                day_report.setFlag("1");
            }
            day_report.setStartTime(oldReport.getStartTime());
            day_report.setUpdateTime(new Date());
            day_report.setStaffStatus(oldReport.getStaffStatus());
            day_reportService.update(day_report);
            return AjaxResult.success("修改成功");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/edit/{reportId}")
    @ResponseBody
    public Object edit(@PathVariable("reportId") Integer id, ModelMap map, HttpServletResponse response) throws Exception {
        map.put("editReport", day_reportService.findById(id));
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");// 设置日期格式
        Date now = df.parse(df.format(new Date()));
        Date beginTime = df.parse("08:00");
        Date endTime = df.parse("9:30");
        Date beginTime2 = df.parse("17:30");
        Date endTime2 = df.parse("20:00");
        if (belongCalendar(now, beginTime, endTime) || belongCalendar(now, beginTime2, endTime2)) {
            return new ModelAndView(prefix + "/edit");
        } else {
            return "false";
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    public AjaxResult deleteById(String ids) {
        day_reportService.deleteById(ids);
        return AjaxResult.success("删除成功");
    }

    @Log(title = "日报管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<DayReport> util = new ExcelUtil<DayReport>(DayReport.class);
        List<DayReport> dayReportList = util.importExcel(file.getInputStream());
        String message = day_reportService.importDayReport(dayReportList, updateSupport);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<DayReport> util = new ExcelUtil<DayReport>(DayReport.class);
        return util.importTemplateExcel("日报数据");
    }

    @GetMapping("/reportExport")
    public String reportExport(ModelMap mmp){
        return prefix+"/export";
    }

    @Log(title = "日报导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(DayReport dayReport) {
        List<DayReport> list = day_reportService.findAllByParamGroup(dayReport);
        ExcelUtil<DayReport> util = new ExcelUtil<DayReport>(DayReport.class);
        return util.exportExcel(list, "日报数据");
    }

    @RequestMapping("/toReport")
    public String toReport() {
        return prefix + "/dayReport";
    }

    @RequestMapping("/lookReport")
    public String lookReport() {
        return prefix + "/dayReportLook";
    }

    //获取员工对象
    //用户表手机号必须与员工表的手机号一致
    private Employee getEmployee() {
        String loginName = ShiroUtils.getLoginName();
        Employee newEmployee = new Employee();
        newEmployee.setMobile(userService.selectUserByLoginName(loginName).getPhonenumber());
        Employee employee = employeeService.selectEmployeeList(newEmployee).get(0);
        return employee;
    }

    /**
     * 判断时间是否在时间段内
     *
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime,
                                         Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }
    @GetMapping("/toAnalysis")
    public String toAnalysis(){
        return prefix+"/analysis";
    }
    @GetMapping("/toAnalysisLine")
    public String toAnalysisline(){
        return prefix+"/analysisLine";
    }
    @GetMapping("/baroption")
    @ResponseBody
    public Map<String,Object> barOption( Employee employee){
        HashMap<String, Object> map = new HashMap<>();
        employee.setDeptId(12);
        List<String> strings = employeeService.selectEnameByDid(employee.getDeptId());
        //当前月日报分析
        Integer[] yes = new Integer[strings.size()];
        Integer[] no = new Integer[strings.size()];
        for (int i = 0; i <= strings.size() - 1; i++) {
            Integer y = dayReportDao.findFlagYByName(strings.get(i));
            Integer n = dayReportDao.findFlagNByName(strings.get(i));
            yes[i] = y;
            no[i] = n;
        }
        //周提交率
         Integer yW = dayReportDao.findFlagNByNameWeekCount("1");

        //本月提交率
         Integer yM = dayReportDao.findFlagNByNameMonthCount( "1");

        //日填报率
        Integer yByNameWeek = dayReportDao.findFlagYByNameWeek("1", -1, 0);
        float[] dayday =new float[2];
        dayday[0] =  ((float)yByNameWeek/(float) strings.size());
        dayday[1] = (float) (1.0-dayday[1]);
        float[] week =new float[2];
        week[0] = (float) (yW/7.0);
        week[1] = (float) (1.0-week[1]);
        float[] month =new float[2];
        month[0] = (float) (yM/30.0);
        month[1] = (float) (1.0-month[1]);

        //今日已更新
       float per = (float) (((float)yByNameWeek/strings.size())*100.0);
        String format = String.format("%.2f", per);


        map.put("yesday",yes);
        map.put("noday",no);
        map.put("ename",strings);
        map.put("weekY",week);
        map.put("monthY",month);
        map.put("dayday",dayday);
        map.put("dayupdate",yByNameWeek);
        map.put("total",format+"%");

        return map;
    }

    @GetMapping("/lineoption")
    @ResponseBody
    public Map<String,Object> lineOption( Employee employee){
        HashMap<String, Object> map = new HashMap<>();
        employee.setDeptId(12);
        List<String> strings = employeeService.selectEnameByDid(employee.getDeptId());
//        //当前月日报分析
//        Integer[] yes = new Integer[strings.size()];
//        Integer[] no = new Integer[strings.size()];
//        for (int i = 0; i <= strings.size() - 1; i++) {
//            Integer y = dayReportDao.findFlagYByName(strings.get(i));
//            Integer n = dayReportDao.findFlagNByName(strings.get(i));
//            yes[i] = y;
//            no[i] = n;
//        }
//        //近一周提交
//        Integer[] week = new Integer[7];
//
//        for (int i = 0; i <= 6; i++) {
//            Integer yW = dayReportDao.findFlagYByNameWeek("1", -i-1,-i);
//            week[6-i] = yW;
//        }
        //近一月提交
        Integer[] month = new Integer[31];
        Integer[] month2 = new Integer[31];
        for (int i = 0; i <= 30; i++) {
            Integer yW = dayReportDao.findFlagYByNameWeek( "1", -i-1,-i);
            Integer yW2 = dayReportDao.findFlagYByNameWeek( "0", -i-1,-i);
            month[30-i] = yW;
            month2[30-i] = yW2;

        }



//        //日填报率
//        Integer yByNameWeek = dayReportDao.findFlagYByNameWeek("1", -1, 0);
//        float[] dayday =new float[2];
//        dayday[1] =  ((float)yByNameWeek/(float) strings.size());
//        dayday[0] = (float) (1.0-dayday[1]);
//
//        //今日已更新
//       float per = (float) (((float)yByNameWeek/strings.size())*100.0);
//        String format = String.format("%.2f", per);


//        map.put("yesday",yes);
//        map.put("noday",no);
        map.put("ename",strings);
//        map.put("weekY",week);
        map.put("monthY",month);
        map.put("monthN",month2);
//        map.put("dayday",dayday);
//        map.put("dayupdate",yByNameWeek);
//        map.put("total",format+"%");

        return map;
    }
}
